package com.abc.robot01.activity

import com.abc.robot01.R
import android.os.Bundle
import android.util.Log
import android.view.View
import androidx.activity.viewModels
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.lazy.grid.GridCells
import androidx.compose.foundation.lazy.grid.LazyVerticalGrid
import androidx.compose.foundation.lazy.grid.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.PagerState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.runtime.livedata.observeAsState
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.ComposeView
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.constraintlayout.compose.Visibility
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.ui.AppBarConfiguration
import com.abc.robot01.databinding.ContentMainBinding
import com.abc.robot01.fragment.VideoFragment
import kotlinx.coroutines.launch
import com.abc.robot01.fragment.H5Fragment
import com.abc.robot01.fragment.PicFragment
import com.abc.robot01.retrofit.RetrofitService
import com.abc.robot01.retrofit.bean.ARTICLE
import com.abc.robot01.retrofit.bean.DESIGN_PACKAGE
import com.abc.robot01.retrofit.bean.LocalConfig
import com.abc.robot01.retrofit.bean.VIDEO
import com.abc.robot01.view.enableFaClick
import com.abc.robot01.view.enableInfoClick
import com.abc.robot01.view.enableSpClick
import com.abc.robot01.vivemodel.HomePageProductViewmodel
import com.abc.robot01.vivemodel.HomePageViewModel
import com.abc.robot01.vivemodel.Robot
import com.bumptech.glide.integration.compose.ExperimentalGlideComposeApi
import com.bumptech.glide.integration.compose.GlideImage
import kotlinx.coroutines.Dispatchers.IO
import org.json.JSONObject

open class BaseActivity : BaseVoiceActivity() {

    private lateinit var appBarConfiguration: AppBarConfiguration
    lateinit var binding: ContentMainBinding

    private val viewModel2: HomePageViewModel by viewModels()

    fun fullScreen(f: Boolean) {
        viewModel2.fullScreen.value = f
        if (f) {
            findViewById<View>(R.id.floating).visibility = View.INVISIBLE
            findViewById<View>(R.id.left).visibility = View.INVISIBLE
        } else {
            findViewById<View>(R.id.floating).visibility = View.VISIBLE
            findViewById<View>(R.id.left).visibility = View.VISIBLE
        }
    }

    override fun handleVoiceCommand(asr: String): Boolean {
        if (asr.contains("商品")) {
            startActivity<ShangPinKuActivity> { }
            playTTS("好的")
            return true
        } else
            if (asr.contains("信息")) {
                startActivity<SysMessageActivity> { }
                playTTS("好的")
                return true
            } else
                if (asr.contains("方案")) {
                    startActivity<FangAnKuActivity> { }
                    playTTS("好的")
                    return true
                }
        return false
    }

    @OptIn(ExperimentalFoundationApi::class)
    private val pagerState = object : PagerState() {
        override val pageCount: Int
            get() = viewModel2.list.size
    }

    fun playPrevious(index: Int) {
        Log.e(TAG, "playPrevious:${index}");
        for (i in index - 1 downTo 0) {
            Log.e(TAG, "playPrevious for000 :${i}");
            if (viewModel2.list[i].type == VIDEO) {
                Log.e(TAG, "playPrevious for:${i}");
                lifecycleScope.launch {
                    pagerState.scrollToPage(i)
                }
                return
            }
        }
    }

    fun playNext(index: Int) {
        Log.e(TAG, "playNext:${index}");
        viewModel2.list.forEachIndexed { index2, item ->
            if (index2 > index) {
                if (item.type == VIDEO)
                    lifecycleScope.launch {
                        Log.e(TAG, "playNext for:${index2}");
                        pagerState.scrollToPage(index2)
                    }
                return@forEachIndexed
            }
        }
    }

    @OptIn(ExperimentalFoundationApi::class)
    @Composable
    fun TopPager(viewModel: HomePageViewModel, onTabSelected: (String, String) -> Unit) {
        val coroutineScope = rememberCoroutineScope()
//        var pageCount = 0;

//        val list= mutableListOf<LocalConfig>()
        val configs = viewModel.configs.collectAsState()
        viewModel.list.clear()
        configs.value.forEach {
            when (it.configType) {
                DESIGN_PACKAGE -> it.configs.forEach {
                    Log.e(TAG, "DESIGN_PACKAGE: " + it.renderUrl)
                    viewModel.list += LocalConfig(
                        type = "DESIGN_PACKAGE",
                        url = it.renderUrl,
                        it.id,
                        it.robotId
                    );
                }

                VIDEO -> {
                    it.configs.forEach {
                        viewModel.list += LocalConfig(
                            type = VIDEO,
                            url = it.fileUrl,
                            configId = it.id,
                            robotId = it.robotId
                        );
                    }
                }

                ARTICLE -> {
                    it.configs.forEach {
                        viewModel.list += LocalConfig(
                            type = "ARTICLE",
                            url = it.fileUrl,
                            configId = it.id,
                            robotId = it.robotId
                        );
                    }
                }
            }
        }

        viewModel.currentPage = pagerState.currentPage;

        if (viewModel.list.size == 0) return

        Column(
            modifier = Modifier.fillMaxSize(),
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Spacer(modifier = Modifier.height(30.px))
            TABIndexer(viewModel)
            HorizontalPager(state = pagerState, userScrollEnabled = true) { page ->
                val current = viewModel.list[page]
                onTabSelected(current.robotId, current.configId)
                when (current.type) {
                    "DESIGN_PACKAGE" -> {
                        FragmentContainer(H5Fragment(current.url))
                    }

                    "VIDEO" -> {
                        FragmentContainer(VideoFragment(current.url, index = page))
                    }

                    "ARTICLE" -> {
                        FragmentContainer(PicFragment(current.url))
                    }
                }
            }
        }
    }

    @Composable
    fun TABIndexer(viewModel: HomePageViewModel) {
        val coroutineScope = rememberCoroutineScope()
        val fullScreen by remember {
            viewModel2.fullScreen
        }
        if (fullScreen.not()) {
            Row {
                viewModel.list.forEachIndexed { index, localConfig ->
                    val selected = pagerState.currentPage == index
                    Box(
                        modifier = Modifier
                            .clickable {
                                coroutineScope.launch {
                                    pagerState.scrollToPage(index)
                                    onTabSelected(localConfig.robotId, localConfig.configId)
                                }
                            }
                            .padding(0.dp)
                            .background(
                                if (selected) Color.White else Card,
                                shape = RoundedCornerShape(0.dp)
                            ) // Custom background and shape
                            .size(width = 100.px, height = 20.px)) {
                    }
                    if (viewModel.list.lastIndex != index)
                        Spacer(modifier = Modifier.width(10.px))
                }
            }
        }
    }

    @OptIn(ExperimentalGlideComposeApi::class)
    @Composable
    fun ProductItem(commodityTreeName: String, pic: String?, id: String) {
        Column(modifier = Modifier.clickable {
            startActivity<XiangQingActivity> {
                putExtra("id", id)
            }
        }) {
//                if(pic != null) {
            GlideImage(
                model = pic ?: R.drawable.sp001,
                contentDescription = "",
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
                    .size(192.px, 192.px),
            )
//                }
//                else
//                Image(
//                    painter = painterResource(id = R.drawable.sp001),
//
//                    contentDescription = "Image",
//                    contentScale = ContentScale.Crop,
//                )
            Spacer(modifier = Modifier.height(14.px))
            Text(
                text = commodityTreeName,
                color = Color.White,
                fontSize = 24.mysp,
                modifier = Modifier
                    .align(Alignment.CenterHorizontally)
            )
        }
    }

    //商品列表
    @Composable
    fun ProductList(viewModel: HomePageProductViewmodel) {
        val configs = viewModel.configs.observeAsState().value ?: return
//        if (configs.code != 200)
//            return
        LazyVerticalGrid(
            contentPadding = PaddingValues(top = 30.px),
            horizontalArrangement = Arrangement.spacedBy(30.px),
            verticalArrangement = Arrangement.spacedBy(30.px),
            columns = GridCells.Fixed(4), // 2 columns in the grid
            modifier = Modifier
                .fillMaxSize()
                .padding(start = 30.px)
        ) {
            items(configs.list) { item ->
                ProductItem(item.name, item.thumbnail, item.commodityId)
            }
        }
    }

    private val viewModel: HomePageProductViewmodel by viewModels()

    //悬浮窗在layout文件里面.
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ContentMainBinding.inflate(layoutInflater)
        setContentView(binding.root)

        //方案库
//    lifecycleScope.launch(IO) {
        Log.e("getDesignPackages", "userId:${Robot.userId}");
        Log.e("getDesignPackages", "companyId:${Robot.companyId}");
        Log.e("getDesignPackages", "accessToken:${Robot.accessToken}");
//    }

        enableFaClick {
            startActivity<FangAnKuActivity>()
        }

        enableSpClick {
            startActivity<ShangPinKuActivity>()
        }

        enableInfoClick() {
            startActivity<SysMessageActivity>()
        }

        //首页商品列表
        val left: ComposeView = findViewById(R.id.left_content)
        left.setContent {
            ProductList(viewModel)
        }

        val composeView: ComposeView = findViewById(R.id.compose_view)

        // Set Compose content
        composeView.setContent {

            // Composable content goes here
            Box(
                modifier = Modifier.fillMaxSize()
            ) {
//                if (fullScreen.not()) {
                //首先是Pager
                TopPager(viewModel2, onTabSelected = ::onTabSelected)
//                }
            }
        }
    }

    private fun onTabSelected(robotId: String, tab: String) {
        viewModel.fetchData(robotId = robotId, homePageConfigId = tab);
    }

    @Composable
    fun FragmentContainer(fragment: Fragment) {
        val fragmentTransaction = supportFragmentManager.beginTransaction()
        fragmentTransaction.replace(R.id.fragment_container, fragment)
        fragmentTransaction.commit()
    }

    companion object {
        val TAG = "BaseActivity"
    }

}
